Railsチュートリアル 11.3.3 演習3
ここまでの演習課題で変更したコードをテストするために、/users と /users/:id の両方に対する統合テストを作成してみましょう。
訳注: update_columnsメソッドは、コールバックとバリデーションを実行せずにスキップしますので、コールバックやバリデーションをかける必要がある場合は注意が必要です。
2ユーザだけテストデータとして用意したい
テストデータ群をusers.ymlに加えてもう1つ用意する方法を調べたが、わからなかった
とりあえず苦肉の策で、User.delete_allしてからUser.newを2回して済ませた
テストデータはtestごとにfixturesをもとに作り直されるので、他のテストに影響はない
code:rb
require "test_helper"
class UsersActivationTest < ActionDispatch::IntegrationTest
def setup
# prepare 2 users
User.delete_all
@activated = User.new({ name: "Michael Example",
email: "michael@example.com",
password: "password",
password_confirmation: "password",
activated: true })
@activated.save
@non_activated = User.new({ name: "non activated user",
email: "non_activated@example.com",
password: "password",
password_confirmation: "password",
activated: false,
activated_at: Time.zone.now })
@non_activated.save
end
test "should not index non-activated user" do
log_in_as(@activated)
get users_path
assert_select "ahref=?", user_path(@activated) assert_select "ahref=?", user_path(@non_activated), count: 0 @non_activated.activate
get users_path
assert_select "ahref=?", user_path(@non_activated), count: 1 end
test "should not show non-activated user" do
log_in_as(@activated)
get user_path(@activated)
assert_template "users/show"
get user_path(@non_activated)
assert_redirected_to root_url
end
end
rmaruon.icon
この演習の解答例を何件か調べた
ページネーションを考慮しているテストはほぼなく、どれも偽陽性の可能性を排除できないものだった 1つだけ「activate: falseのユーザーを1ページ目に作る」という方針の記事があった
IDの採番順とページングの順は保証されているのだろうか?(要検証)
保証されていたとしても、テストデータの追加で簡単にこのテストが壊れてしまうので、私は良くない方針だと思う